<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChatGPT-like Chat Interface</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: auto;
            padding: 10px;
        }
        #chatBox {
            border: 1px solid #ccc;
            padding: 10px;
            height: 400px;
            overflow-y: scroll;
            margin-bottom: 10px;
        }
        .message {
            padding: 5px;
            border-radius: 5px;
            margin-bottom: 5px;
        }
        .user {
            background-color: #e0f7fa;
            text-align: right;
        }
        .assistant {
            background-color: #e8f5e9;
        }
        #userInput {
            width: 100%;
            padding: 10px;
            font-size: 16px;
        }
    </style>
</head>
<body>

<h1>ChatGPT-like Interface</h1>

<div id="chatBox"></div>
<input type="text" id="userInput" placeholder="Type a message..." onkeydown="if(event.key === 'Enter') sendMessage()">

<script>
    // 保存对话历史记录，维持上下文
    let conversationHistory = [];

    // 将消息添加到聊天窗口
    function displayMessage(role, content) {
        const chatBox = document.getElementById('chatBox');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}`;
        messageDiv.innerText = content;
        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    // 发送消息到后端并处理响应
    function sendMessage() {
        const userInput = document.getElementById('userInput');
        const messageContent = userInput.value.trim();

        if (!messageContent) return; // 空消息不处理
        displayMessage('user', messageContent);
        userInput.value = '';

        // 构建用户消息并添加到对话历史
        conversationHistory.push({ role: 'user', content: messageContent });

        // 发送请求到后端
        fetch('http://localhost:8098/ai/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(conversationHistory)
        })
            .then(response => response.text()) // 接收纯文本响应
            .then(assistantMessage => {
                // 显示助手的回复并更新对话历史
                displayMessage('assistant', assistantMessage);
                conversationHistory.push({ role: 'assistant', content: assistantMessage });
            })
            .catch(error => {
                console.error('Error:', error);
                displayMessage('assistant', 'Error: Could not get response');
            });
    }
</script>

</body>
</html>
